<?php

namespace App\Http\Controllers\Home;

use App\Models\Areas;
use App\Models\Categorys;
use App\Models\Collections;
use App\Models\Configs;
use App\Models\Footprints;
use App\Models\Goods;
use App\Models\GoodsCategorys;
use App\Models\GoodsEvaluates;
use App\Models\Orders;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class GoodsController extends Controller
{
    /**
     * 商品分类页面
     * @param url home.goods.goodsCate
     * @param Request $request
     * @return bool
     */
    public function goodsCate(){
        $title = '商品分类';
        return view('home.goods.cate',compact('title'));
    }
    /**
     * 商品列表页面
     * @param url home.goods.goodsList
     * @param Request $request
     * @return bool
     */
    public function goodsList(){
        $title = '商品列表';
        return view('home.goods.list',compact('title'));
    }
    /**
     * 商品详情页面
     * @param url home.goods.goodsDetails
     * @param Request $request
     * @return bool
     */
    public function goodsDetails(Request $request){
        $title = '商品详情';
        $is_evaluate = (int)$request->get('is_evaluate');//是否为评价跳转
        return view('home.goods.details',compact('title','is_evaluate'));
    }

    /**
     * 商品分类
     * @param url home.goods.goodsCatesApi
     * @param Request $request
     * @return bool
     * @return salenum 销量
     * @return $lists['goods_hot']热门商品  $lists['goods_new']最新商品
     */
    public function goodsCatesApi(Request $request)
    {
        try{
            $lists = [];
            $lists['goods_cate'] = GoodsCategorys::getCascaderList();
            foreach ($lists['goods_cate'] as $key=>$val){
                $lists['goods_cate'][$key]['bool'] = false;
            }
            $fields = ['id','title','thumb','price','content','salenum','view','credit','cate_id','cate_pid','type'];
            $lists['goods_hot'] = Goods::allLists(['hot'=>2], $fields, null, 6, 'salenum');
            $lists['goods_new'] = Goods::allLists([], $fields, null, 6, 'created_at');
            foreach ($lists['goods_hot'] as $key=>$val){
                $lists['goods_hot'][$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                $lists['goods_hot'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
            }
            foreach ($lists['goods_new'] as $key=>$val){
                $lists['goods_new'][$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                $lists['goods_new'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 商品列表
     * @param url home.goods.goodsListsApi
     * @param Request $request
     * @param keyword 热搜词条
     * @param cid 一级分类id
     * @param cid_id 二级分类id
     * @param page 页码
     * @param sid 排序id 1:销量 2:浏览量 3:好评量 4:积分商品(积分兑换专区)  不传或其他值：创建时间
     * @param orderby 'desc'倒叙 ‘asc'正序
     * @return bool
     */
    public function goodsListsApi(Request $request)
    {
        try{
            $map = [
                'keyword' => (string)$request->get('keyword'),//热搜词条
                'cid' => (int)$request->get('cid'),//一级分类id
                'cid_id' => (int)$request->get('cid_id'),//二级分类id
            ];
            if (!empty($map['cid_id'])){
                $map['cid_id'] = explode(",", $map['cid_id']);
            }
            $page = (int)$request->get('page',1);//页码
            $sid = (int)$request->get('sid',2);//排序
            $orderby = (string)$request->get('orderby','desc');//排序方式
            $sort = 'created_at';
            if ($sid == 1){
                $sort = 'salenum';
            }elseif ($sid == 2){
                $sort = 'view';
            }elseif ($sid == 3){
                $sort = 'praise';
            }elseif ($sid == 4){
                $map['type'] = 3;
            }else{
                $sort = 'created_at';
            }
            $lists = [];
            $lists['cate_id'] = GoodsCategorys::getcates(['pid'=>0],['id','name','pid']);//一级分类
            //二级分类
            if(empty($map['cid'])){
                $cate_ids = GoodsCategorys::where('pid',0)->where('status','<>',-1)->orderBy('sort','asc')->pluck('id')->toArray();
                $field = " field(pid,".implode(',',$cate_ids)."),sort";
                $lists['children'] = GoodsCategorys::whereIn('pid',$cate_ids)->orderByRaw($field)->get(['id','name','pid'])->toArray();
//                $lists['children'] = GoodsCategorys::where('pid','<>','0')->orderBy('sort','asc')->get(['id','name','pid'])->toArray();
            }else{
                $lists['children'] = GoodsCategorys::getcates(['pid'=>$map['cid']],['id','name','pid'])->toArray();
            }
            $fields = ['id','title','thumb','price','content','view','salenum','credit','cate_id','cate_pid','type'];
            $lists['goods'] = Goods::allLists($map, $fields, $page, 12, $sort, $orderby);
            foreach ($lists['goods'] as $key=>$val){
                $lists['goods'][$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                $lists['goods'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
            }

            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 商品详情
     * @param url home.goods.goodsDetailsApi
     * @param Request $request
     * @param id 商品id
     * @param type 1:好评 2：中评 3：差评
     * @param page 页码（评价数据）
     * @return avg_good 好评率
     * @return good 好评数
     * @return middle 中评数
     * @return bad 差评数
     * @return is_collect 1:未收藏 2:已收藏
     * @return (array)store 主办方信息
     * @return store_collect 店铺1:未收藏 2:已收藏
     * @return (array)evaluates 评价数据
     * @return average_star 当前评价的平均星星
     * @return type 类型：1好评，2中评，3差评
     * @return content 内容
     * @return user_avatar 用户头像
     */
    public function goodsDetailsApi(Request $request){
        try{
            $id = (int)$request->get('id');//商品id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $fields = ['id','store_id','title','thumb','images','price','content','star','cate_id','cate_pid','type'];
            $lists = Goods::details(['id'=>$id], $fields);

            //判断是否收藏
            $lists['is_collect'] = 1;//默认未收藏
            $userinfo = auth()->guard('web')->user();//获取当前登录用户
            if (!empty($userinfo)){
                if ($userinfo['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$id,'user_id'=>$userinfo['id'],'type'=>3])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 1 : 2;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $userinfo['id'],
                    'foot_id' => $id,
                    'type'    => 3,
                ];
                $foot_id = Footprints::where($foot_arr)->value('id');
                if($foot_id > 0){
                    Footprints::where($foot_arr)->update(['updated_at'=>date('Y-m-d H:i:s')]);
                }else{
                    Footprints::create($foot_arr);
                }
            }
            //店铺信息
            if($lists['type'] == 3){
                $base = Configs::getConfig('base');
                $lists['store'] = ['logo'=>$base['site_logo'],'name'=>$lists['store_name'],'link'=>['master_name'=>'','master_phone'=>'']];
            }else{
                $field = ['id','user_id','store_name','logo','call','credit','view','service','hot','quality','cate_id'];
                $store = Stores::details(['id'=>$lists['store_id']], $field);
                $store['call'] = strlen($store['call'])>=4 ? '999+' : $store['call'];
                $store['view'] = strlen($store['view'])>=4 ? '999+' : $store['view'];
                $store['service'] = strlen($store['service'])>=4 ? '999+' : $store['service'];
                $store['link'] = ['master_name'=>'','master_phone'=>''];
                $store['bool'] = false;
                //获取当前店铺所属用户的区域
                $area_id = Users::where('id',$store['user_id'])->where('status','<>',-1)->value('area');
                $store['area'] = Areas::where('id',$area_id)->where('status','<>',-1)->value('name');
                //擅长领域
                if (!empty($store['cate_id'])){
                    $cate_id = explode(',',$store['cate_id']);
                    foreach ($cate_id as $kk => $vv){
                        $pidTree[] = Categorys::where(['id'=>$vv])->first('name');
                    }
                }else{
                    $pidTree['name'] = [];
                }
                $store['cate_name'] = $pidTree;
                //判断是否收藏
                $store['store_collect'] = 1;//默认未收藏
                if (!empty($userinfo) && $userinfo['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$id,'user_id'=>$userinfo['id'],'type'=>4])->value('collect_id');
                    $store['store_collect'] = empty($collect) ? 1 : 2;
                }
                $lists['store'] = $store;
            }
            //评价内容
            $page = (int)$request->get('page',1);//页码
            if (empty($page)) return $this->writeJson(1,null,'页码不能为空');
            $map = [
                'goods_id' => $lists['id'],
                'type' => (int)$request->get('type',1),
            ];
            $evaluates = GoodsEvaluates::allLists($map, ['*'], $page, 3);
            foreach ($evaluates as $k=>$v){
                $evaluates[$k]['user_name'] = '**'.mb_substr($v['user_name'],-2,4,"utf-8");
            }
            $sum = GoodsEvaluates::counts(['goods_id'=>$lists['id']]);//评价总数
            $good = GoodsEvaluates::counts(['goods_id'=>$lists['id'],'type'=>1]);//好评数
            $middle = GoodsEvaluates::counts(['goods_id'=>$lists['id'],'type'=>2]);//中评数
            $bad = GoodsEvaluates::counts(['goods_id'=>$lists['id'],'type'=>3]);//差评数

            $lists['sum'] = $sum;//评价总数
            $lists['good'] = strlen($good)>=4 ? '999+' : $good;//好评数
            $lists['middle'] = strlen($middle)>=4 ? '999+' : $middle;
            $lists['bad'] = strlen($bad)>=4 ? '999+' : $bad;
            $lists['avg_good'] = empty($sum) ? 100 : intval(round (($good/$sum)*100));//好评率
            $lists['evaluates'] = $evaluates;

            Goods::where('id',$id)->increment('view');//浏览量加1
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 商品详情右侧同类型热门商品
     * @param url home.goods.detailsRightHotGoodsApi
     * @param cid 商品一级分类id
     * @param type 商品类型
     */
    public function detailsRightHotGoodsApi(Request $request)
    {
        try{
            $params = [];
            $type = (int)$request->get('type');//商品类型
            if($type == 3){
                $params['type'] = 3;
            }else{
                $params['cid'] = (int)$request->get('cid');//商品一级分类id
            }
            $fields = ['id','thumb','title','cate_pid','cate_id','price','salenum','view','credit','type'];
            $lists = Goods::allLists($params,$fields, null,4,'salenum');
            foreach ($lists as $key=>$val){
                $lists[$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 商品收藏
     * @param url home.goods.goodsCollectApi
     * @param Request $request
     * @param collect_id 收藏内容id
     * @return bool
     */
    public function goodsCollectApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status']);
            if (empty($userinfo)){
                return $this->writeJson(1,null,'用户不存在,请联系客服!');
            }else{
                if($userinfo['status'] == 2){
                    return $this->writeJson(1, null,'账户正在审核中，请等待审核!');
                }elseif($userinfo['status'] == 3){
                    return $this->writeJson(1, null,'账号未通过审核，请前往个人中心查看原因并重新提交审核!');
                }elseif ($userinfo['status'] == 4){
                    return $this->writeJson(1, null,'账号已锁定，请前往个人中心查看原因或联系客服!');
                }
                if ($userinfo['type'] != 1) return $this->writeJson(1,null,'供应商不能收藏商品!');
            }

            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return $this->writeJson(1,null,'参数错误');
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>3])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 3,
                ];
                Collections::create($params);
                Goods::where('id',$collect_id)->increment('collect');
                return $this->writeJson(0, null, '收藏成功');
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>3])->delete();
                return $this->writeJson(0, null, '取消收藏成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

}